package com.ruoyi.form.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.form.base.StringUtils;
import com.ruoyi.form.domain.*;
import com.ruoyi.form.service.IAxModelFieldService;
import com.ruoyi.form.service.IAxFieldService;
import com.ruoyi.form.service.IAxModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Controller
 *
 * @author LZF
 * @date 2025-07-16
 */
@RestController
@RequestMapping("/form/config/field")
public class AxFieldController extends BaseController {
    @Autowired
    private IAxFieldService axFieldService;
    @Autowired
    private IAxModelFieldService axFrontGridService;
    @Autowired
    private IAxModelService axModelService;

/**
 * 查询【请填写功能名称】列表
 */
@PreAuthorize("@ss.hasPermi('system:field:list')")
@GetMapping("/list")
    public TableDataInfo list(AxField axField) {
        startPage();
        List<AxField> list = axFieldService.selectAxFieldList(axField);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:field:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AxField axField) {
        List<AxField> list = axFieldService.selectAxFieldList(axField);
        ExcelUtil<AxField> util = new ExcelUtil<AxField>(AxField.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:field:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(axFieldService.selectAxFieldById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:field:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AxField axField) {
        return toAjax(axFieldService.insertAxField(axField));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:field:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AxField axField) {
        return toAjax(axFieldService.updateAxField(axField));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:field:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(axFieldService.deleteAxFieldByIds(ids));
    }

    /***********************************************************************************************/
    /**
     * 获取代码、序号
     */
    @GetMapping(value = "/getCodeSortNum")
    public String getCodeSortNum() {
        String basicCode = axFieldService.getBasicCode();
        Integer sortNum = axFieldService.getMaxSortNum();
        return basicCode + ":" + sortNum;
    }
    /**
     * 查询引用属性列表
     */
    @GetMapping("/reflist")
    public TableDataInfo reflist(AxField axField) {
        startPage();
        List<AxField> list = axFieldService.queryRefAttributelistForModel(axField);
        return getDataTable(list);
    }

    /**
     * 查询引用属性列表(选择引用属性时)
     * @param axField
     * @return {@link TableDataInfo}
     */
    @GetMapping("/selectReflist")
    public TableDataInfo selectReflist(AxField axField) {
        if (StringUtils.isNotEmpty(axField.getModelId())) {
            QueryWrapper<AxModelField> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("model_id", axField.getModelId());
            if (StringUtils.isNotEmpty(axField.getConfigFieldType())) {
                if ("filter".equals(axField.getConfigFieldType())) {
                    queryWrapper.isNotNull("filter_position");
                    queryWrapper.ne("filter_position", "");
                    queryWrapper.orderByAsc("filter_sort_num");
                } else if ("table".equals(axField.getConfigFieldType())) {
                    queryWrapper.eq("show_flag", "0");
                    queryWrapper.orderByAsc("sort_num");
                }
            } else {
                queryWrapper.eq("show_flag", "1");
                queryWrapper.isNull("filter_position");
                queryWrapper.orderByDesc("update_time");
                queryWrapper.orderByDesc("create_time");
            }
            List<AxModelField> gridlist = axFrontGridService.list(queryWrapper);
            List<String> frontGridIdList = gridlist.stream().map(bean -> bean.getFieldId()).collect(Collectors.toList());
            axField.setFrontGridIdList(frontGridIdList);
        }
        startPage();
        List<AxField> list = axFieldService.querySelectRefAttributelist(axField);
        return getDataTable(list);
    }
    /**
     * 保存引用属性 模型附属属性
     * @param axField
     * @return {@link AjaxResult}
     */
    @PostMapping("/addRef")
    public AjaxResult addRef(@RequestBody AxField axField) {
        return toAjax(axFieldService.insertRefBo(axField));
    }
    /**
     * 查询模型引用属性(表单显示设计器用)
     * @param axField
     * @return {@link List< Element>}
     */
    @GetMapping("/emlist")
    public List<Element> emlist(AxField axField) {
        return axFieldService.emlist(axField);
    }
    /**
     * 查询模型引用属性(表单显示设计器用，显示的属性)
     * @param axField
     * @return {@link List<Element>}
     */
    @GetMapping("/layoutList")
    public FieldLayout layoutList(AxField axField)
    {
        return axFieldService.layoutList(axField);
    }
    /**
     * 保存表单显示设置布局
     * @param fieldLayout
     * @return {@link AjaxResult}
     */
    @PostMapping("/saveLayout")
    public AjaxResult saveLayout(@RequestBody FieldLayout fieldLayout) {
        //保存模板表单尺寸、标签对齐、标签宽度
        AxModel model = axModelService.selectAxModelById(fieldLayout.getModelId());
        model.setFormSize(fieldLayout.getFormSize());
        model.setLabelPosition(fieldLayout.getLabelPosition());
        model.setLabelWidth(fieldLayout.getLabelWidth());
        axModelService.updateAxModel(model);

        AxModelField bussFrontGrid = new AxModelField();
        bussFrontGrid.setModelId(fieldLayout.getModelId());
        bussFrontGrid.setParentId(fieldLayout.getParentId());
        List<AxModelField> bussFrontGrids = axFrontGridService.queryRefList(bussFrontGrid);
        Boolean ret = axFieldService.saveLayout(fieldLayout, bussFrontGrids);
        return toAjax(ret);
    }
    /**
     * 删除引用属性
     * @param axField
     * @return {@link AjaxResult}
     */
    @PostMapping("/delRef")
    public AjaxResult delRef(@RequestBody AxField axField) {
        axFieldService.delRefBo(axField);
        return success();
    }
}
